#include "BlockStoreDelegate.h"
#include "BlockStoreModel.h"
#include <QApplication>
#include <QStyleOptionViewItem>

BlockStoreDelegate::BlockStoreDelegate(QObject *parent)
    : QStyledItemDelegate(parent)
{
}

void BlockStoreDelegate::paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    if (!index.isValid())
        return;

    // 获取数据
    QString text = index.data(Qt::DisplayRole).toString();
    bool isAvailable = (index.data(Qt::UserRole).toInt() == BlockStoreModel::Available);

    // 绘制背景
    if (option.state & QStyle::State_Selected) {
        painter->fillRect(option.rect, option.palette.highlight());
    } else {
        painter->fillRect(option.rect, option.palette.base());
    }

    // 绘制块项目
    drawBlockItem(painter, option.rect, text, isAvailable);
}

QSize BlockStoreDelegate::sizeHint(const QStyleOptionViewItem &option, const QModelIndex &index) const
{
    Q_UNUSED(option)
    Q_UNUSED(index)
    return QSize(120, 40); // 设置单元格大小
}

void BlockStoreDelegate::drawBlockItem(QPainter *painter, const QRect &rect, const QString &text, bool isAvailable) const
{
    // 绘制文本
    QPen pen = painter->pen();
    pen.setColor(Qt::black);
    painter->drawRect(rect.adjusted(2, 2, -2, -2));
    // 计算圆形指示器的位置和大小
    int circleSize = qMin(rect.width(), rect.height()) - 10;
    int textWidth = painter->fontMetrics().horizontalAdvance(text);
    
    // 圆形指示器位置（右侧）
    QRect circleRect(rect.right() - circleSize - 5, 
                    rect.center().y() - circleSize / 2,
                    circleSize, circleSize);
    
    // 文本位置（左侧）
    QRect textRect(rect.left() + 5, rect.top(), 
                  rect.width() - circleSize - 15, rect.height());

    
    QFont font = painter->font();
    font.setPointSize(20);
    painter->setFont(font);
    painter->drawText(textRect, Qt::AlignCenter, text);

    painter->save();
    // 绘制圆形状态指示器
    QColor circleColor = isAvailable ? QColor(0, 255, 0) : QColor(200, 200, 200);
    painter->setBrush(QBrush(circleColor));
    painter->setPen(QPen(QColor(100,100,100), 1));
    painter->setRenderHint(QPainter::Antialiasing);
    painter->drawEllipse(circleRect);
    painter->restore();
}
